using Godot;
using Godot.Collections;
using System;

public partial class ObjectInteractable : Interactable
{
	[Export]
	public string name = "";
	private Player _player;
	private UiInteractTips _uiInteractTips;
	private GuiViewManager _guiViewManager;
	private TaskManager _taskManager;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		CollisionLayer = 0;
		CollisionMask = 0;
		SetCollisionMaskValue(2,true);
		BodyEntered += OnInteractableBodyEntered;
		BodyExited += OnInteractableBodyExited;

		var Game = GetNode<Game>("/root/Game");
		_player = Game.get_player();
		_guiViewManager = Game.get_main().GetNode<GuiViewManager>("%GuiViewManager");
		_taskManager = _player.GetNode<TaskManager>("%TaskManager");
		_uiInteractTips = _guiViewManager.GetChild(0).GetNode<UiInteractTips>("UiInteractTips");

		if(this.tips == "")
		{tips = "检查";}
		
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

    public override void Interact()
    {
		CheckTask();
		UpdateTextKey();
        //显示文字
		var DialogManager = GetNode<DialogManager>("/root/DialogManager");
		DialogManager.DisplayDialog(tips,this.name);
    }

    public override void OnInteractableBodyEntered(Node2D player)
    {
        base.OnInteractableBodyEntered(player);
    }
	public override void OnInteractableBodyExited(Node2D player)
    {
        base.OnInteractableBodyExited(player);
    }

	public void UpdateTextKey()
	{
		if(!(this.GetParent() is Characters))
		{return;}
		Characters character = this.GetParent() as Characters;
		foreach(var tasksList in character.CharacterData.tasksList)
		{
			if(tasksList.Value)
			{
				character.CharacterData.textkey = tasksList.Key;
				break;
			}
			else
			{
				character.CharacterData.textkey = "text";
			}
		}
		var Game = GetNode<Game>("/root/Game");
		MessageManager messageManager = Game.get_message_manager();
		messageManager.EmitSignal("DialogStart",this.GetParent());
	}

	public void CheckTask()
	{
		if(!(this.GetParent() is Characters))
		{return;}
		Characters character = this.GetParent() as Characters;
		var Game = GetNode<Game>("/root/Game");
		foreach(var taskInPlayer in _taskManager.runningTasks)
		{
			foreach(var taskInNPC in character.CharacterData.tasksList)
			{
				if(taskInNPC.Key == taskInPlayer.Name)
				{
					string waitingtask = taskInNPC.Key + "_waiting";
					character.CharacterData.textkey = waitingtask;
					break;
				}
			}
		}
	}
}
